package com.code.spring.mvcframework.servlet;

import com.code.spring.mvcframework.annotation.SoulAutowired;
import com.code.spring.mvcframework.annotation.SoulController;
import com.code.spring.mvcframework.annotation.SoulRequestMapping;
import com.code.spring.mvcframework.annotation.SoulService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * @author: liyufei
 * @date: 2021-05-15 11:53
 */
@Slf4j
public class SoulDispatcherServlet extends HttpServlet {

    // 代表application.properties配置文件，代替application.xml文件
    private Properties contextConfig = new Properties();

    // 保存扫描到的所有的类名
    private List<String> classNames = Lists.newArrayList();

    // 传说中的ioc容器
    private Map<String, Object> ioc = Maps.newHashMap();

    // 传说中的handlerMapping容器，保存url和method的映射关系
    private Map<String, Method> handlerMapping = Maps.newHashMap();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    /**
     * 运行阶段
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 6.运行时阶段请求调用
        try {
            doDispatch(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().write("500 Exception, Detail: " + Arrays.toString(e.getStackTrace()));
        }

    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        // 绝对路径
        String url = req.getRequestURI();
        // 处理成相对路径
        String contextPath = req.getContextPath();
        url = url.replaceAll(contextPath, "").replaceAll("/+", "/");

        if (!this.handlerMapping.containsKey(url)) {
            resp.getWriter().write("404 Not Found!!!");
            return;
        }

        Method method = this.handlerMapping.get(url);

        String beanName = toLowerFirstCase(method.getDeclaringClass().getSimpleName());

        Map<String, String[]> parameterMap = req.getParameterMap();
        method.invoke(ioc.get(beanName), new Object[] {req, resp, parameterMap.get("name")[0]});

    }


    /**
     * 初始化阶段
     * @param config
     * @throws ServletException
     */
    @Override
    public void init(ServletConfig config) throws ServletException {

        // 1.加载配置文件
        doLoadConfig(config.getInitParameter("contextConfigLocation"));

        // 2.扫描相关的类
        doScanner(contextConfig.getProperty("scanPackage"));

        // 3.初始化扫描到的类，并将它们放入到IOC容器中
        doInstance();

        // 4.完成依赖注入
        doAutowired();

        // 5.初始化HandlerMapping
        initHandlerMapping();

        log.info("soul framework init is ok.");
    }

    //初始化url和Method的一对一对应关系
    private void initHandlerMapping() {
        if(ioc.isEmpty()){ return; }

        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Class<?> clazz = entry.getValue().getClass();

            if(!clazz.isAnnotationPresent(SoulController.class)){continue;}


            //保存写在类上面的@GPRequestMapping("/demo")
            String baseUrl = "";
            if(clazz.isAnnotationPresent(SoulRequestMapping.class)){
                SoulRequestMapping requestMapping = clazz.getAnnotation(SoulRequestMapping.class);
                baseUrl = requestMapping.value();
            }

            //默认获取所有的public方法
            for (Method method : clazz.getMethods()) {
                if(!method.isAnnotationPresent(SoulRequestMapping.class)){continue;}

                SoulRequestMapping requestMapping = method.getAnnotation(SoulRequestMapping.class);
                //优化
                // //demo///query
                String url = ("/" + baseUrl + "/" + requestMapping.value())
                        .replaceAll("/+","/");
                handlerMapping.put(url,method);
                System.out.println("Mapped :" + url + "," + method);

            }


        }


    }

    private void doAutowired() {
        if (!ioc.isEmpty()) return;

        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            //Declared 所有的，特定的 字段，包括private/protected/default
            //正常来说，普通的OOP编程只能拿到public的属性
            Field[] fields = entry.getValue().getClass().getDeclaredFields();
            for (Field field : fields) {
                if (!field.isAnnotationPresent(SoulAutowired.class)) continue;

                SoulAutowired autowired = field.getAnnotation(SoulAutowired.class);
                //如果用户没有自定义beanName，默认就根据类型注入
                //这个地方省去了对类名首字母小写的情况的判断，这个作为课后作业
                //小伙伴们自己去完善
                String beanName = autowired.value().trim();
                if ("".equals(beanName)) {
                    //获得接口的类型，作为key待会拿这个key到ioc容器中去取值
                    beanName = field.getType().getName();
                }

                //如果是public以外的修饰符，只要加了@Autowired注解，都要强制赋值
                //反射中叫做暴力访问， 强吻
                field.setAccessible(true);

                try {
                    // 用反射机制，动态给字段赋值
                    field.set(entry.getValue(), ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    log.error("autowired error.", e);
                }

            }
        }
    }

    private void doInstance() {
        //初始化，为DI做准备
        if(classNames.isEmpty()){return;}

        try {
            for (String className : classNames) {
                Class<?> clazz = Class.forName(className);

                //什么样的类才需要初始化呢？
                //加了注解的类，才初始化，怎么判断？
                //为了简化代码逻辑，主要体会设计思想，只举例 @Controller和@Service,
                // @Componment...就一一举例了
                if(clazz.isAnnotationPresent(SoulController.class)){
                    Object instance = clazz.newInstance();
                    //Spring默认类名首字母小写
                    String beanName = toLowerFirstCase(clazz.getSimpleName());
                    ioc.put(beanName,instance);
                }else if(clazz.isAnnotationPresent(SoulService.class)){
                    //1、自定义的beanName
                    SoulService service = clazz.getAnnotation(SoulService.class);
                    String beanName = service.value();
                    //2、默认类名首字母小写
                    if("".equals(beanName.trim())){
                        beanName = toLowerFirstCase(clazz.getSimpleName());
                    }

                    Object instance = clazz.newInstance();
                    ioc.put(beanName,instance);
                    //3、根据类型自动赋值,投机取巧的方式
                    for (Class<?> i : clazz.getInterfaces()) {
                        if(ioc.containsKey(i.getName())){
                            throw new Exception("The “" + i.getName() + "” is exists!!");
                        }
                        //把当前类实现的所有的接口的类型直接当成key了
                        ioc.put(i.getName(),instance);
                    }
                }else {
                    continue;
                }

            }
        }catch (Exception e){
            log.error("类初始化失败", e);
        }
    }

    //如果类名本身是小写字母，确实会出问题
    //但是我要说明的是：这个方法是我自己用，private的
    //传值也是自己传，类也都遵循了驼峰命名法
    //默认传入的值，存在首字母小写的情况，也不可能出现非字母的情况

    //为了简化程序逻辑，就不做其他判断了，大家了解就OK
    //其实用写注释的时间都能够把逻辑写完了
    private String toLowerFirstCase(String simpleName) {
        char [] chars = simpleName.toCharArray();
        //之所以加，是因为大小写字母的ASCII码相差32，
        // 而且大写字母的ASCII码要小于小写字母的ASCII码
        //在Java中，对char做算学运算，实际上就是对ASCII码做算学运算
        chars[0] += 32;
        return String.valueOf(chars);
    }

    private void doScanner(String scanPackage) {
        // scanPackage=com.code.spring
        // 转换为文件路径，实际上就是把 . 变为 /
        // classpath -
        URL url = this.getClass().getClassLoader().getResource("/" + scanPackage.replaceAll("\\.", "/"));
        File classpath = new File(url.getFile());
        for (File file : classpath.listFiles()) {
            // 递归处理所有类文件，当然这里要过滤掉类路径下的非 .java 文件
            if (file.isDirectory()) {
                // 如果是目录，调自己
                doScanner(scanPackage + "." + file.getName());
            } else {
                if (!file.getName().endsWith(".class")) continue;

                // 获取类名
                String className = scanPackage + "." + file.getName().replace(".class", "");
                // 将扫描的类保存到集合中
                classNames.add(className);
            }
        }

    }

    /**
     * 加载spring主配置文件application.properties内容到Properties类
     * @param contextConfigLocation
     */
    private void doLoadConfig(String contextConfigLocation) {

        // 从类路径下直接找到spring的主配置文件
        InputStream inputStream = null;
        inputStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);

        try {
            // 加载application.properties配置文件
            contextConfig.load(inputStream);
        } catch (IOException e) {
            log.error("加载application.properties配置文件失败", e);
        } finally {
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
